package com.qingcheng.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.wxpay.sdk.WXPayConfig;
import com.github.wxpay.sdk.WXPayRequest;
import com.github.wxpay.sdk.WXPayUtil;
import com.qingcheng.config.WXConfig;
import com.qingcheng.service.order.OrderService;
import com.qingcheng.service.pay.WeixinPayService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author:boy
 * @Date:2019/7/21
 * @description:
 * @ModifiedBy:
 */
@Service(interfaceClass = WeixinPayService.class)
public class WeixinPayServiceImpl implements WeixinPayService {
    @Autowired
    private WXConfig wxConfig;
    @Reference
    private OrderService orderService;

    public Map ctreateNative(String orderId, Integer money, String notifyUrl) {
        try {
            Map<String, String> param = new HashMap<String, String>();
            param.put("appid", wxConfig.getAppID());//公众号
            param.put("mch_id", wxConfig.getMchID());//商户号
            param.put("nonce_str", WXPayUtil.generateNonceStr());//随机字 符串
            param.put("body", "青橙");//商品描述
            param.put("out_trade_no", orderId);//商户订单号
            param.put("total_fee", money + "");//总金额（分）
            param.put("spbill_create_ip", "127.0.0.1");//IP
            param.put("notify_url", notifyUrl);//暂时随便写一个
            param.put("trade_type", "NATIVE");//交易类型
            String xmlParam = WXPayUtil.generateSignedXml(param, wxConfig.getKey());
            WXPayRequest request = new WXPayRequest(wxConfig);
            String xmlResult = request.requestWithCert("/pay/unifiedorder", null, xmlParam, false);
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xmlResult);
            Map<String, String> map = new HashMap<String, String>();
            map.put("code_url", resultMap.get("code_url"));
            map.put("total_fee", money + "");
            map.put("out_trade_no", orderId);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return new HashMap();
        }
    }

    public void notifyLogic(String xml) {
        try {
            Map<String, String> map = WXPayUtil.xmlToMap(xml);
            boolean valid = WXPayUtil.isSignatureValid(map, wxConfig.getKey());
            System.out.println("签名是否正确："+valid);
            System.out.println(map.get("out_trade_no"));
            System.out.println(map.get("result_code"));
            if (valid){
                orderService.updatePayStatus(map.get("out_trade_no"),map.get("transaction_id") );
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
